/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 #include <hi_time.h>
include "ultrasonic_module.h"


/*Measure distance from obstacles ahead*/
hi_float get_distance(hi_void)
{
    static hi_u64 start_time = 0;
    hi_u64 end_time = 0;
    hi_float distance = 0.0;
    hi_gpio_value val = HI_GPIO_VALUE0;
    int gpio_8_level = GPIO_8_IS_LOW_LEVEL;

    /*超声波echo口，设置为输入模式*/
    hi_io_set_func(HI_IO_NAME_GPIO_8, HI_IO_FUNC_GPIO_8_GPIO);
    hi_gpio_set_dir(HI_GPIO_IDX_8, HI_GPIO_DIR_IN);

    /* 给trig发送至少10us的高电平脉冲，以触发传感器测距 */
    hi_gpio_set_ouput_val(HI_GPIO_IDX_7, HI_GPIO_VALUE1);
    hi_udelay(20);
    hi_gpio_set_ouput_val(HI_GPIO_IDX_7, HI_GPIO_VALUE0);

    /*计算与障碍物之间的距离*/
    printf("测距中...\n");
    int count = 0;
    while (1)
    {
        hi_gpio_get_input_val(HI_GPIO_IDX_8, &val);

        /*echo为高电平时开始计时*/
        if ((val == HI_GPIO_VALUE1) && (gpio_8_level == GPIO_8_IS_LOW_LEVEL))
        {
            start_time = hi_get_us();
            gpio_8_level = GPIO_8_IS_HIGH_LEVEL;
        }

        /*echo为低电平时纪录结束时间*/
        if ((val == HI_GPIO_VALUE0) && (gpio_8_level == GPIO_8_IS_HIGH_LEVEL))
        {
            end_time = hi_get_us() - start_time;
            start_time = 0;
            break;
        }
        if (count % 1000 == 0)
        {
            end_time = 0;
            start_time = 0;
            hi_udelay(1000);
            /* 给trig发送至少10us的高电平脉冲，以触发传感器测距 */
            hi_gpio_set_ouput_val(HI_GPIO_IDX_7, HI_GPIO_VALUE1);
            hi_udelay(20);
            hi_gpio_set_ouput_val(HI_GPIO_IDX_7, HI_GPIO_VALUE0);
        }
        if (count > 100000)
        {
            printf("测距失败。。。。\n");
            break;
        }
        count++;
    }
    distance = end_time / DISTANCE_FORMULA;

    return distance;
}